'use strict';

var constant = require('../../const');
var models = require('../../models');
var crypto = require('crypto');
var debug = require('debug');
var request = require('request');
var WXPay = require('weixin-pay');
var fs = require('fs');
var AV = require('leanengine')

var wxpay = WXPay({
	appid: 'wx07b56150c7843b91',
	mch_id: '1306542201',
	partner_key: 'xiaocankejiwudutuan2016zhuanqian', //微信商户平台API密钥
	pfx: fs.readFileSync(__dirname + '/apiclient_cert.p12'), //微信商户平台证书
});

var config = {
	"sign_type": "MD5",
	"alipay_gateway": "https://mapi.alipay.com/gateway.do?",
	"https_verify_url": "https://mapi.alipay.com/gateway.do?service=notify_verify&",
	"partner": "2088811117366572",
	"key": "iqy7npb2mh1m42pkzqthgclhk34jflmw",
	"notify_url": "http://www.wudutuan.com/member/pay/alinotify",
	// "return_url": "http://moliantest.avosapps.om/pay/return"

}

var defaultParams_wap = {
	service: 'alipay.wap.create.direct.pay.by.user',
	//service: 'create_direct_pay_by_user',
	partner: config.partner,
	'_input_charset': 'utf-8',
	//支付类型，必填，不能修改
	payment_type: '1',
	notify_url: config.notify_url,
	// return_url: config.return_url
	//卖家支付宝帐户，必填
	seller_id: "2088811117366572",
};

var defaultParams_web = {
	service: 'create_direct_pay_by_user',
	partner: config.partner,
	'_input_charset': 'utf-8',
	//支付类型，必填，不能修改
	payment_type: '1',
	notify_url: config.notify_url,
	// return_url: config.return_url
	//卖家支付宝帐户，必填
	seller_id: "2088811117366572",
	//	paymethod:"bankPay",
	//	defultbank:"ICBCB2C"
};


function getMemberPayIndex(req, res) {
	var phone = req.query.phone;
	var type = parseInt(req.query.type)
	var ip = req.headers['x-real-ip'];

	var query = new AV.Query(models.MLUser);
	query.equalTo("mobilePhoneNumber", phone);
	query.find({
		success: function(users) {
			if (users.length == 0) {
				var data = {
					"code": 101,
					"message": "该手机号未注册，请去app注册",
					"wxpay_url": "",
					"alipay_url": ""
				};
				res.render('alipay/memberPay', data);
			} else {
				var user = users[0];
				if (user.get('level') == -1) {
					var data = {
						"code": 102,
						"message": "您资料未通过审核，请去app重新提交",
						"wxpay_url": "",
						"alipay_url": ""
					};
					res.render('alipay/memberPay', data);
				} else {
					//定义price
					var level = user.get("level");
					var gender = user.get('gender');
					var price;
					var levelname;
					if (level == 2) {
						price = gender == 2 ? 19 : 29;
						levelname = "白金会员";
					} else if (level == 1) {
						price = gender == 2 ? 29 : 39;
						levelname = "黄金会员";
					} else {
						price = gender == 2 ? 39 : 49;
						levelname = "普通会员";
					}

					//weixin 支付
					wxpay.createUnifiedOrder({
						body: '会员支付',
						out_trade_no: _creatTradNo(phone),
						total_fee: price * 100,
						//						total_fee: 1,
						spbill_create_ip: ip,
						notify_url: 'http://www.wudutuan.com/member/pay/wxnotify',
						trade_type: 'NATIVE',
						product_id: '001'
					}, function(err, result) {
						var data = {
							"code": 0,
							"levelname": levelname,
							"price": price,
							"wxpay_url": result.code_url,
							"alipay_url": _createAliLink(price, phone, type)
						};
						res.render('alipay/memberPay', data);
					});
				}
			}

		},
		error: function(error) {
			var data = {
				"code": 101,
				"message": "该手机号未注册，请去app注册",
				"wxpay_url": "",
				"alipay_url": ""
			};
			res.render('alipay/memberPay', data);
		}
	});
}

//生成支付宝链接
function _createAliLink(price, phone, type) {
	var defaultParams = type == 0 ? defaultParams_web : defaultParams_wap;
	//	price = 0.01;
	console.log(defaultParams)
	var params = {
		//商户网站订单系统中唯一订单号，必填
		out_trade_no: _creatTradNo(phone),
		//订单名称，必填
		subject: phone + " memberPay",
		// 付款金额，必填
		total_fee: price,
		// 订单描述
		body: price + "yuan",
	};
	var url1 = "https://mapi.alipay.com/gateway.do?"
	var finalParams = JSON.parse(JSON.stringify(defaultParams));
	for (var k in params) {
		finalParams[k] = params[k];
	}
	var reqParams = buildRequestPara(finalParams);
	for (k in reqParams) {
		url1 += k + "=" + reqParams[k] + "&";
	}
	console.log(url1)
	return url1;
}

//生成订单号码
function _creatTradNo(phone) {
	var time = _dataFomat(new Date());
	var num = Math.ceil(Math.random() * 99999999);
	return time + num + phone;
}

function _dataFomat(date) {
	var fmt = "yyyyMMdd";
	var o = {
		"M+": date.getMonth() + 1, //月份 
		"d+": date.getDate(), //日 
		"h+": date.getHours(), //小时 
		"m+": date.getMinutes(), //分 
		"s+": date.getSeconds(), //秒 
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度 
		"S": date.getMilliseconds() //毫秒 
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

// 生成及时到账交易请求 html
function getDirectPayReqHtml(params, strMethod) {
	var finalParams = JSON.parse(JSON.stringify(defaultParams));
	for (var k in params) {
		finalParams[k] = params[k];
	}
	//debug('params: %j', finalParams);
	var result = '<form id="alipaysubmit" name="alipaysubmit"' +
		' action="' + config.alipay_gateway + '"' +
		' method="' + strMethod + '">';
	var reqParams = buildRequestPara(finalParams);
	console.log(reqParams);
	for (k in reqParams) {
		result += '<input type="hidden" name="' + k + '" value="' + reqParams[k] + '"/><br />';
	}
	//submit按钮控件请不要含有name属性
	result += '<script>document.forms["alipaysubmit"].submit();</script>';
	debug('generate request html:', result);
	return result;
};

// 验证消息是否是支付宝发出的合法消息
function verify(params, cb) {
	//判断responsetTxt是否为true
	//responsetTxt的结果不是true，与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
	if (!params.notify_id) {
		debug('verify err: notify_id is null.');
		return cb(null, false);
	}
	verifyResponse(params.notify_id, function(err, result) {
		if (err || !result) {
			debug('verify err:', err || result);
			return cb(err, false);
		}
		//判断 verifySign 是否为true
		//如果不是true，与安全校验码、请求时的参数格式（如：带自定义参数等）、编码格式有关
		if (verifySign(params, params.sign || '')) {
			return cb(null, true);
		}
		return cb(null, false);
	});
};

// 获取远程服务器ATN结果,验证返回URL
var verifyResponse = function(notifyId, cb) {
	var verifyUrl = config.https_verify_url + 'partner=' + config.partner + "&notify_id=" + notifyId;
	debug(verifyUrl);
	request(verifyUrl, function(err, res, body) {
		if (err) {
			return cb(err, false);
		}
		if (res.statusCode != 200) {
			debug('verify err:', body);
			return cb(null, false);
		}
		debug('verify result:', body);
		cb(null, body === 'true');
	});
};

var verifySign = function(params, sign) {
	if (config.sign_type === 'MD5') {
		var paramsStr = createLinkString(paraFilter(params));
		var mySign = crypto.createHash('md5').update(paramsStr + config.key).digest('hex');
		return sign == mySign;
	}
	return false;
};

var buildRequestPara = function(params) {
	var reqParams = paraFilter(params);
	var paramsStr = createLinkString(reqParams);
	if (config.sign_type === 'MD5') {
		reqParams.sign = crypto.createHash('md5').update(paramsStr + config.key).digest('hex');
		//debug('build request params: paramsString=' + paramsStr + ', sign=' + reqParams.sign);
		reqParams.sign_type = config.sign_type;
	} else {
		reqParams.sign = '';
	}
	return reqParams;
};

// 除去数组中的空值和签名参数
var paraFilter = function(params) {
	var result = {};
	if (!params) {
		return result;
	}
	for (var k in params) {
		if (!params[k] || params[k] === '' || k === 'sign' || k === 'sign_type') {
			continue;
		}
		result[k] = params[k];
	}
	return result;
};

// 将所有参数按照“参数=参数值”的模式用“&”字符拼接成字符串
var createLinkString = function(params) {
	var result = '';
	var sortKeys = Object.keys(params).sort();
	for (var i in sortKeys) {
		result += sortKeys[i] + '=' + params[sortKeys[i]] + '&';
	}
	if (result.length > 0) {
		return result.slice(0, -1);
	} else {
		return result.toString("utf-8");
	}
};


/////============================notify===============
function alinotify(req, res) {
	var phone = req.body.subject.split("+")[0];
	var sn = req.body.out_trade_no;
	var price = parseInt(req.body.price);
	var body = req.body;
	typeof(body) === 'string' ? body = JSON.parse(body): body;

	verify(req.body, function(err, result) {
		if (result == true) {
			console.log("chengg")
			var query = new AV.Query(models.MLUser);
			query.equalTo("mobilePhoneNumber", phone);
			query.find({
				success: function(users) {
					if (users.length > 0) {
						var user = users[0];
						user.set('isUserInited', 1); //改为资料完整
						user.save(null, {
							success: function() {
								var ConsumeRecord = models.MLConsumeRecord;
								var record = new ConsumeRecord();
								record.set('money', price);
								record.set('user', users[0]);
								record.set('remark', '会员入会,支付宝支付' + price);
								record.set('sn', sn);
								record.set('type', constant.CONSUME_TYPE_JOIN);
								record.save(null, {
									success: function() {
										AV.Cloud.run('sendSysMsg', {
											"touserId": user.id,
											"type": 0,
											"msg": "恭喜你入会缴费成功。"
										}, {
											success: function(result) {

											},
											error: function(error) {

											}
										});

									},
									error: function(record, error) {
										console.log(error)
									}
								});
							},
							error: function(user, error) {
								console.log(error);
							}
						});
					}
				},
				error: function(error) {
					console.log(error);
				}
			});
		}
		res.send("success");
	});

}

exports.wxnotify = wxpay.useWXCallback(function(msg, req, res, next) {
	console.log(msg);
	if (msg.result_code == "SUCCESS") {
		var sn = msg.out_trade_no;
		var price = parseInt(msg.total_fee) / 100;
		var phone = msg.out_trade_no.substring(16);

		var query = new AV.Query(models.MLUser);
		query.equalTo("mobilePhoneNumber", phone);
		query.find({
			success: function(users) {
				if (users.length > 0) {
					var user = users[0];
					user.set('isUserInited', 1); //改为资料完整
					user.save(null, {
						success: function() {
							var ConsumeRecord = models.MLConsumeRecord;
							var record = new ConsumeRecord();
							record.set('money', price);
							record.set('user', users[0]);
							record.set('remark', '会员入会,微信支付' + price);
							record.set('sn', sn);
							record.set('type', constant.CONSUME_TYPE_JOIN);
							record.save(null, {
								success: function() {
									AV.Cloud.run('sendSysMsg', {
										"touserId": user.id,
										"type": 0,
										"msg": "恭喜你入会缴费成功。"
									}, {
										success: function(result) {
											res.send({
												"code": 0,
												"msg": "发送成功"
											});
										},
										error: function(error) {
											res.send({
												"code": 1,
												"msg": "发送失败"
											});
										}
									});

								},
								error: function(record, error) {
									console.log(error)
								}
							});
						},
						error: function(user, error) {
							console.log(error);
						}
					});
				}
			},
			error: function(error) {
				console.log(error);
			}
		});
	}
	res.send("success");
})


exports.getMemberPayIndex = getMemberPayIndex;
exports.alinotify = alinotify;